package oop.ex3.serverprotocol;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.LinkedList;

import oop.ex3.nameserver.NameServer;
import oop.ex3.sharedclasses.IPaddress;

/**
 * Handles WANTFILE Message.
 * handles a client's request to get all the FileManagers known to 
 * the NameServer that contain a certain file.
 * @author zablo
 *
 */
public class WantFile extends ClientMessageHandler{

	@Override
	public boolean run(NameServer server, IPaddress sessionIP,
			DataInputStream clientInput, DataOutputStream clientOutput) {
		try {
			String wantedFile=clientInput.readUTF();
			
			if (endsWithEnd(clientInput)==FAILURE){
				// WANTFILE message doesn't end with END.
				return FAILURE;
			}
			
			LinkedList<IPaddress> fileSources=server.getFileSources(wantedFile);
			
			if (fileSources.isEmpty()){
				if (ServerMessageSender.fileNotFound(clientOutput)==FAILURE){
					return FAILURE;
				}
			}
			else{
				for (IPaddress fileSource: fileSources){
					if (ServerMessageSender.fileAddress
											(clientOutput, fileSource)==FAILURE){
							return FAILURE;
						}
				}
				//END LIST
				if (ServerMessageSender.endList(clientOutput)==FAILURE){
					return FAILURE;
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return FAILURE;
		}
		
		return SUCCESS;
	}

}
